"""连接侧边栏组件，包含数据库连接和MQTT连接配置。"""

from __future__ import annotations

from PySide6.QtWidgets import (
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QVBoxLayout,
    QWidget,
)


class ConnectionSidebar(QWidget):
    """连接侧边栏，包含数据库连接和MQTT连接配置。"""

    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        
        # MQTT配置区域（将在setup_mqtt_config中设置）
        self._mqtt_config_box: QGroupBox | None = None
        # 数据库配置区域（将在setup_db_config中设置）
        self._db_config_box: QGroupBox | None = None
        
        self._setup_layout()
    
    def setup_mqtt_config(
        self,
        host_input: QLineEdit,
        port_input: QLineEdit,
        username_input: QLineEdit,
        password_input: QLineEdit,
        username_visibility_btn: QPushButton,
        password_visibility_btn: QPushButton,
        connect_btn: QPushButton,
        status_indicator: QLabel,
        status_label: QLabel,
    ) -> None:
        """设置MQTT配置区域，将MQTT相关的widgets添加到侧边栏。
        
        Args:
            host_input: Host输入框
            port_input: Port输入框
            username_input: 用户名输入框
            password_input: 密码输入框
            username_visibility_btn: 用户名显示/隐藏按钮
            password_visibility_btn: 密码显示/隐藏按钮
            connect_btn: 连接按钮
            status_indicator: 状态指示器
            status_label: 状态标签
        """
        # 创建MQTT配置组框
        self._mqtt_config_box = QGroupBox("MQTT 连接配置")
        self._mqtt_config_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                font-size: 13px;
                color: #333;
                border: 2px solid #e0e0e0;
                border-radius: 6px;
                margin-top: 12px;
                padding-top: 12px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 12px;
                padding: 0 6px;
            }
        """)
        
        form_layout = QFormLayout(self._mqtt_config_box)
        form_layout.setHorizontalSpacing(10)
        form_layout.setVerticalSpacing(8)
        form_layout.setContentsMargins(12, 16, 12, 12)
        
        # 设置输入框样式
        for field in (host_input, port_input, username_input, password_input):
            field.setMinimumHeight(28)
        
        host_input.setPlaceholderText("Broker Host")
        port_input.setPlaceholderText("Port")
        port_input.setMaximumWidth(120)
        username_input.setPlaceholderText("用户名（可选）")
        password_input.setPlaceholderText("密码（可选）")
        
        # 为用户名输入框创建容器，包含输入框和显示按钮
        username_container = QWidget()
        username_layout = QHBoxLayout(username_container)
        username_layout.setContentsMargins(0, 0, 0, 0)
        username_layout.setSpacing(8)
        username_layout.addWidget(username_input)
        username_layout.addWidget(username_visibility_btn)
        
        # 为密码输入框创建容器，包含输入框和显示按钮
        password_container = QWidget()
        password_layout = QHBoxLayout(password_container)
        password_layout.setContentsMargins(0, 0, 0, 0)
        password_layout.setSpacing(8)
        password_layout.addWidget(password_input)
        password_layout.addWidget(password_visibility_btn)
        
        # 状态容器
        status_container = QWidget()
        status_layout = QHBoxLayout(status_container)
        status_layout.setContentsMargins(0, 0, 0, 0)
        status_layout.setSpacing(8)
        status_layout.addWidget(status_indicator)
        status_layout.addWidget(status_label)
        
        # 连接按钮容器
        button_container = QWidget()
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(8)
        connect_btn.setMinimumHeight(30)
        button_layout.addWidget(connect_btn)
        button_layout.addStretch()
        
        # 添加表单行，每个参数一行
        form_layout.addRow("Host", host_input)
        form_layout.addRow("Port", port_input)
        form_layout.addRow("用户名", username_container)
        form_layout.addRow("密码", password_container)
        form_layout.addRow("状态", status_container)
        form_layout.addRow("", button_container)  # 连接按钮单独一行
        
        # 将MQTT配置区域添加到布局的顶部
        layout = self.layout()
        if layout:
            layout.insertWidget(0, self._mqtt_config_box, 0)  # 插入到顶部，不拉伸，固定大小
    
    def setup_db_config(
        self,
        host_input: QLineEdit,
        port_input: QLineEdit,
        database_input: QLineEdit,
        user_input: QLineEdit,
        password_input: QLineEdit,
        password_visibility_btn: QPushButton,
        connect_btn: QPushButton,
        status_indicator: QLabel,
        status_label: QLabel,
    ) -> None:
        """设置数据库配置区域，将数据库相关的widgets添加到侧边栏。
        
        Args:
            host_input: Host输入框
            port_input: Port输入框
            database_input: 数据库名称输入框
            user_input: 用户名输入框
            password_input: 密码输入框
            password_visibility_btn: 密码显示/隐藏按钮
            connect_btn: 连接按钮
            status_indicator: 状态指示器
            status_label: 状态标签
        """
        # 创建数据库配置组框
        self._db_config_box = QGroupBox("数据库连接配置")
        self._db_config_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                font-size: 13px;
                color: #333;
                border: 2px solid #e0e0e0;
                border-radius: 6px;
                margin-top: 12px;
                padding-top: 12px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 12px;
                padding: 0 6px;
            }
        """)
        
        form_layout = QFormLayout(self._db_config_box)
        form_layout.setHorizontalSpacing(10)
        form_layout.setVerticalSpacing(8)
        form_layout.setContentsMargins(12, 16, 12, 12)
        
        # 设置输入框样式
        for field in (host_input, port_input, database_input, user_input, password_input):
            field.setMinimumHeight(28)
        
        host_input.setPlaceholderText("数据库 Host")
        port_input.setPlaceholderText("Port")
        port_input.setMaximumWidth(120)
        database_input.setPlaceholderText("数据库名称")
        user_input.setPlaceholderText("用户名")
        password_input.setPlaceholderText("密码")
        
        # 为密码输入框创建容器，包含输入框和显示按钮
        password_container = QWidget()
        password_layout = QHBoxLayout(password_container)
        password_layout.setContentsMargins(0, 0, 0, 0)
        password_layout.setSpacing(8)
        password_layout.addWidget(password_input)
        password_layout.addWidget(password_visibility_btn)
        
        # 状态容器
        status_container = QWidget()
        status_layout = QHBoxLayout(status_container)
        status_layout.setContentsMargins(0, 0, 0, 0)
        status_layout.setSpacing(8)
        status_layout.addWidget(status_indicator)
        status_layout.addWidget(status_label)
        
        # 连接按钮容器
        button_container = QWidget()
        button_layout = QHBoxLayout(button_container)
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(8)
        connect_btn.setMinimumHeight(30)
        button_layout.addWidget(connect_btn)
        button_layout.addStretch()
        
        # 添加表单行，每个参数一行
        form_layout.addRow("Host", host_input)
        form_layout.addRow("Port", port_input)
        form_layout.addRow("数据库", database_input)
        form_layout.addRow("用户名", user_input)
        form_layout.addRow("密码", password_container)
        form_layout.addRow("状态", status_container)
        form_layout.addRow("", button_container)  # 连接按钮单独一行
        
        # 将数据库配置区域添加到布局中（在MQTT配置之后）
        layout = self.layout()
        if layout:
            # 获取当前MQTT配置的位置索引
            mqtt_index = layout.indexOf(self._mqtt_config_box) if self._mqtt_config_box else -1
            if mqtt_index >= 0:
                # 在MQTT配置之后插入数据库配置
                layout.insertWidget(mqtt_index + 1, self._db_config_box, 0)
            else:
                # 如果没有MQTT配置，添加到顶部
                layout.insertWidget(0, self._db_config_box, 0)
    
    def setup_template_buttons(
        self,
        edit_topic_template_btn: QPushButton,
        edit_message_template_btn: QPushButton,
    ) -> None:
        """设置模板编辑按钮区域。
        
        Args:
            edit_topic_template_btn: 编辑Topic模板按钮
            edit_message_template_btn: 编辑消息模板按钮
        """
        # 创建模板配置按钮容器
        self._template_buttons_container = QWidget()
        self._template_buttons_container.setStyleSheet("""
            QWidget {
                background-color: #f8f9fa;
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
            }
        """)
        
        buttons_layout = QVBoxLayout(self._template_buttons_container)
        buttons_layout.setContentsMargins(8, 8, 8, 8)
        buttons_layout.setSpacing(8)
        
        # 标题
        title_label = QLabel("模板配置")
        title_label.setStyleSheet("font-weight: bold; font-size: 13px; color: #333;")
        buttons_layout.addWidget(title_label)
        
        # 按钮
        edit_topic_template_btn.setMinimumHeight(32)
        edit_topic_template_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 4px;
                font-weight: 500;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #138496;
            }
            QPushButton:pressed {
                background-color: #117a8b;
            }
        """)
        
        edit_message_template_btn.setMinimumHeight(32)
        edit_message_template_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 4px;
                font-weight: 500;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        
        buttons_layout.addWidget(edit_topic_template_btn)
        buttons_layout.addWidget(edit_message_template_btn)
        
        # 将按钮容器添加到布局底部（在stretch之前）
        layout = self.layout()
        if layout:
            # 移除stretch
            stretch_index = layout.count() - 1
            if stretch_index >= 0:
                item = layout.itemAt(stretch_index)
                if item and item.spacerItem():
                    layout.removeItem(item)
            
            # 添加按钮容器
            layout.addWidget(self._template_buttons_container, 0)
            
            # 重新添加stretch（在按钮容器之后）
            layout.addStretch()

    def _setup_layout(self) -> None:
        """设置布局。"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(8, 8, 8, 8)
        layout.setSpacing(8)
        # MQTT配置区域和数据库配置区域将在setup_mqtt_config和setup_db_config中添加
        # 添加stretch确保内容靠上显示，同时保持与其他列的高度一致
        layout.addStretch()
        
        # 模板配置按钮区域（在底部）
        self._template_buttons_container: QWidget | None = None

